package scenetracer.core.shader;

import java.util.ArrayList;
import java.util.List;

import scenetracer.SceneState;
import scenetracer.SceneTracer;
import scenetracer.core.Primitive;
import scenetracer.core.Ray;
import scenetracer.core.Scene;
import scenetracer.core.Texture;
import scenetracer.core.light.Light;
import scenetracer.core.light.PointLight;
import scenetracer.core.primitive.IntersectionState;
import scenetracer.image.Color;
import scenetracer.math.Point3;
import scenetracer.math.Vector3;

public class DiffuseShader extends Shader {

	public void setTexture(String texturePath) {		
		
		tex = new Texture(texturePath);
	
	}
	
	public void setDiffColor(Color diffColor) {
		this.dColor = diffColor;
	}
	
	public DiffuseShader(String name,int  penumbra) {
		super(name, penumbra);
		this.type = "diffuse";
	}

	@Override
	public void setPrim(Primitive primitive) {
		primitive.setDiffuseK(1f);	
	}
	
	@Override
	public void shade(SceneState state) {
		
		Color aLColor = new Color(Color.BLACK);
		
		SceneTracer trace = state.getTracer();
		Scene scene = state.getScene();
		int hits;
		
		Color color = state.getColor();
		Vector3 normal = state.getNormal();
		Primitive primitive = state.getPrimitive();
		Color diffuseC = new Color(0, 0, 0);
		
		
		Point3 interPoint = state.getIntersection().getIntersectionPoint();
		float coeff = 0;
		
		for (Light l : scene.getLights()) {	
			List<Vector3> dirs = null;

			if(penumbra > 0)
			{
				Point3 tmpInterPoint = new Point3(interPoint);
				color.add(getPenumbraColor(color, normal, primitive, state, scene, l, tmpInterPoint));
			}
			else {
				dirs = l.getDirLights(state.getIntersection());
			
			
			
				hits = 0;
				float atte = l.getAtte(interPoint);
				for (Vector3 lDir : dirs) {
					
						if(!trace.lightObs(scene, new Ray(interPoint, lDir), l, primitive))
							hits++;	
						
												
				}
				
				if(hits > 0){
					coeff = Vector3.dot(dirs.get(0), normal);
	
					if( coeff > 0){
						Color.mul(atte*(CORRECTION), l.getColor(), aLColor);
						
						aLColor.mul((float)hits / dirs.size());;
						Color.mul(getPointColor(primitive, interPoint), aLColor, diffuseC);
						color.madd(coeff, diffuseC);
					}			
				}
		}	}
	}
	
	
	
	
}
